﻿Imports System.Data.OleDb

' Generic logic for a model with an ID field.
'
' Includes database access methods and logic for:
' - creation
' - loading from the database
' - keeping track of whether it needs saving

Public MustInherit Class Model
    Private Shared connectionString = ConfigurationManager.ConnectionStrings("quizzes_db_ConnectionString").ConnectionString
    Protected IsInDB As Boolean
    Protected _isSaved As Boolean
    Private _id As String

    Public ReadOnly Property IsSaved
        Get
            Return _isSaved
        End Get
    End Property

    ' This is public only because the class
    ' NeonLearn needs to reference it. Once I can
    ' delete the NeonLearn.db property, I can
    ' make this protected.
    Public Shared ReadOnly Property db As OleDbConnection
        Get
            Dim connection As OleDbConnection = New OleDbConnection(connectionString)
            connection.Open()
            Return connection
        End Get
    End Property

    Public Shared Function GetField(Of T)(ByRef obj As T, ByVal dr As OleDbDataReader, ByVal fieldName As String, ByVal notFound As T)
        Dim field As Object = dr(fieldName)
        If IsDBNull(field) Then
            obj = notFound
            Return False
        Else
            obj = CType(field, T)
            Return True
        End If
    End Function

    Public ReadOnly Property ID As String
        Get
            Return _id
        End Get
    End Property

    Protected MustOverride Function Load() As Boolean
    Public MustOverride Function Save() As Boolean
    Protected MustOverride Sub CreateBlank()

    Protected Sub New(ByVal newId As String, ByVal dontLoad As Boolean)
        _id = newId
        If Not dontLoad AndAlso Load() Then
            IsInDB = True
            _isSaved = True
        Else
            CreateBlank()
            IsInDB = False
            _isSaved = False
        End If
    End Sub

    Public Sub New(ByVal newId As String)
        Me.New(newId, False)
    End Sub
End Class
